class myPromise {
  static PENDING = 'pending';
  static FULFILLED = 'fulfilled';
  static REJECTED = 'rejected'
  constructor(executor) {
    this.status = myPromise.PENDING
    this.result = null
    this.resovleCallbacks = []
    this.rejectCallbacks = []
    try {
      executor(this.resolve.bind(this), this.reject.bind(this))
    }
    catch (e) {
      this.reject(e)
    }
  }
  resolve (result) {
    setTimeout(() => {
      if (this.status === myPromise.PENDING) {
        this.status = myPromise.FULFILLED
        this.result = result
        this.resovleCallbacks.forEach(fn => fn(result))
      }
    })
  }
  reject (result) {
    setTimeout(() => {
      if (this.status === myPromise.FULFILLED) {
        this.status = myPromise.REJECTED
        this.result = result
        this.rejectCallbacks.forEach(fn => fn(result))
      }
    })
  }
  then (onFulfilled, onRejected) {
    let promise2 = new myPromise((resolve, reject) => {
      onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : () => { }
      onRejected = typeof onRejected === 'function' ? onRejected : () => { }
      if (this.status === myPromise.PENDING) {
        this.resovleCallbacks.push(onFulfilled)
        this.rejectCallbacks.push(onRejected)
      }
      if (this.status === myPromise.FULFILLED) {
        onFulfilled()
      }
      if (this.status === myPromise.REJECTED) {
        onRejected()
      }
    })
    return promise2

  }
}
let p = new myPromise((resolve, reject) => {
  resolve('成功了')
})
p.then((result) => {
  console.log('第一次then', result)
  return 111
})
p.then(res => {
  console.log('第二个then', res)
})
// let a = new Promise((resolve, reject) => {
//   resolve('开始了')
// })
// a.then(res => {
//   console.log('第一个then')
//   return res + '3333'
// }).then(res => {
//   console.log('接收到的第二then', res)
// })
// console.log('结束了')